package com.quanxiaoha.weblog.web.controller;

import com.quanxiaoha.weblog.common.aspect.ApiOperationLog;
import com.quanxiaoha.weblog.common.utils.Response;
import com.quanxiaoha.weblog.common.utils.UserContextHolder;
import com.quanxiaoha.weblog.web.service.RecommendationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 推荐系统控制器
 */
@RestController
@RequestMapping("/recommendation")
@Api(tags = "推荐系统")
@Slf4j
public class RecommendationController {

    @Autowired
    private RecommendationService recommendationService;

    @Autowired
    private UserContextHolder userContextHolder;

    @GetMapping("/personalized")
    @ApiOperation(value = "获取个性化推荐")
    @ApiOperationLog(description = "获取个性化推荐")
    public Response getPersonalizedRecommendations(
            @ApiParam("推荐数量") @RequestParam(defaultValue = "10") int limit) {
        
        Long userId = userContextHolder.getCurrentUserId();
        if (userId == null) {
            // 未登录用户返回热门推荐
            return recommendationService.getPopularRecommendations(limit);
        }
        
        return recommendationService.getPersonalizedRecommendations(userId, limit);
    }

    @GetMapping("/popular")
    @ApiOperation(value = "获取热门推荐")
    @ApiOperationLog(description = "获取热门推荐")
    public Response getPopularRecommendations(
            @ApiParam("推荐数量") @RequestParam(defaultValue = "10") int limit) {
        return recommendationService.getPopularRecommendations(limit);
    }

    @GetMapping("/similar/{articleId}")
    @ApiOperation(value = "获取相似文章推荐")
    @ApiOperationLog(description = "获取相似文章推荐")
    public Response getSimilarArticleRecommendations(
            @ApiParam("文章ID") @PathVariable Long articleId,
            @ApiParam("推荐数量") @RequestParam(defaultValue = "5") int limit) {
        return recommendationService.getSimilarArticleRecommendations(articleId, limit);
    }

    @PostMapping("/behavior")
    @ApiOperation(value = "记录用户行为")
    @ApiOperationLog(description = "记录用户行为")
    public Response recordUserBehavior(
            @ApiParam("文章ID") @RequestParam Long articleId,
            @ApiParam("行为类型：1-浏览，2-点赞，3-收藏，4-分享") @RequestParam Integer behaviorType) {
        
        Long userId = userContextHolder.getCurrentUserId();
        if (userId == null) {
            return Response.fail("用户未登录");
        }
        
        return recommendationService.recordUserBehavior(userId, articleId, behaviorType);
    }
}
